﻿Imports MindFusion.Scheduling
Imports MindFusion.Scheduling.WinForms
Imports System.Drawing.Drawing2D

Public Class FrmPlanningB

    Private szSQL As String
    Private rs As ADODB.Recordset
    Private centered As StringFormat
    Private DerniereValidation As Date

    Private Sub FrmPlanningB_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Me.Text = "PLANNING " & gTypePlanning
        ' définir l'orientation du texte
        centered = New StringFormat
        centered.Alignment = StringAlignment.Center
        centered.LineAlignment = StringAlignment.Center

        rb_JOURNEE.Checked = True     ' affichage par journée
        ' initialiser la date à aujourd'hui
        TE_DATE.Value = Format(Now, "yyyy/MM/dd")
        ' affichage à la journée
        CAL_PLANNING.CurrentView = CalendarView.ResourceView
        CAL_PLANNING.GroupType = GroupType.GroupByResources
        CAL_PLANNING.Date = TE_DATE.Value
        CAL_PLANNING.EndDate = CAL_PLANNING.Date.AddHours(23)
        CAL_PLANNING.CurrentTime = CAL_PLANNING.Date
        CAL_PLANNING.ResourceViewSettings.TimelineScale = 190
        CAL_PLANNING.ResourceViewSettings.BottomTimelineSettings.Format = "H:mm"
        TE_CD_MON.Clear()
        ' a supprimer
        BO_SEMAINE_TYPE.Visible = False
        LoadPlanning()

    End Sub

    ' Load le planning par Journée
    Sub LoadPlanning()
        Dim noResource As Integer = 0

        Me.Cursor = Cursors.WaitCursor
        ' effacer la sélection
        CAL_PLANNING.Selection.Reset()
        CAL_PLANNING.ResetDrag()
        ' effacer le calendrier
        CAL_PLANNING.Schedule.Clear()
        CAL_PLANNING.Resources.Clear()

        Dim resource As Resource = Nothing

        If rb_JOURNEE.Checked = True Then
            ' Affichage par journée, disposer les moniteurs présents en coordonnées
            szSQL = "CALL spGet_MONITEURS_AFF_byAGENCE(" & gUserAgence & ",'" & Format(CAL_PLANNING.Date, "yyyy/MM/dd") & "','" & Format(CAL_PLANNING.EndDate, "yyyy/MM/dd") & _
                    "','" & gTypePlanning & "')"
            GetRecordset(ctDSN_AEM, szSQL, rs)

            Do While Not rs.EOF
                resource = New Resource
                resource.Name = rs.Fields("intitule").Value
                '  & vbNewLine & _
                '  rs.Fields("dmatin").Value & "h-" & rs.Fields("fmatin").Value & "h et " & rs.Fields("dsoir").Value & "h-" & rs.Fields("fsoir").Value & "h"
                resource.Id = rs.Fields("cd_mon").Value
                CAL_PLANNING.BeginInit()
                ' créer la ressource moniteur
                CAL_PLANNING.Resources.Add(resource)
                ' ajouter les RDV de la journée dans le planning
                LoadRendezVous(CAL_PLANNING.Date, CAL_PLANNING.EndDate, resource.Id, noResource)
                CAL_PLANNING.EndInit()
                ' save 1er moniteur trouvé
                If TE_CD_MON.TextLength = 0 Then
                    TE_CD_MON.Text = resource.Id
                    TE_MONITEUR.Text = resource.Name
                End If
                rs.MoveNext()
                noResource = noResource + 1
            Loop
            rs.Close()
            resource = Nothing
        Else
            CAL_PLANNING.BeginInit()
            ' Affichage par semaine, disposer les heures en coordonnées
            LoadRendezVous(CAL_PLANNING.Date, CAL_PLANNING.EndDate, TE_CD_MON.Text, noResource)
            CAL_PLANNING.EndInit()
            ' positionner le planning sur 6h
            CAL_PLANNING.VScrollPos = 5
        End If
        Me.Cursor = Cursors.Default


        If gUserAcces < 9 Then
            BO_DEVALIDER.Visible = False
        Else
            BO_DEVALIDER.Visible = True
        End If
        BO_VALIDER.Text = "Valider " & Format(TE_DATE.Value, "dd/MM/yyyy")

    End Sub

    Private Sub BO_VALIDER_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BO_VALIDER.Click

        Dim nStatut As Integer

        If IsUserAuthorised(4) = False Then
            Exit Sub
        End If
        If MsgBox("Après la validation, aucune modification ne sera possible." & vbNewLine & _
                  "Voulez-vous valider la journée du " & Format(TE_DATE.Value, "dd/MM/yyyy") & " ?", MsgBoxStyle.OkCancel) = MsgBoxResult.Cancel Then
            Exit Sub
        End If

        Me.Cursor = Cursors.WaitCursor

        ' Lire les inscrits du groupe
        szSQL = "CALL spGet_ELEVES_CPT_byDATE(" & gUserAgence & ",'" & Format(TE_DATE.Value, "yyyy/MM/dd") & "','PLA')"
        GetRecordset(ctDSN_AEM, szSQL, rs)
        Do While Not rs.EOF
            ' rdv non validé ?
            If IsDate(rs.Fields("date_valeur").Value) = False Then
                nStatut = rs.Fields("statut").Value
                If nStatut = 0 Then
                    nStatut = 1
                End If
                gCD_CLI = rs.Fields("cd_cli").Value
                ' valider la ligne
                UpdatePlanningB(nStatut, rs.Fields("no_ligne").Value)
                ' marque le rdv comme validé
                szSQL = "UPDATE eleves_cpt SET date_valeur=Now(), statut=" & nStatut & ",intitule=getIntituleStatut(intitule, statut)" & _
                        " WHERE no_ligne=" & rs.Fields("no_ligne").Value
                ExecQuery(ctDSN_AEM, szSQL)
                ' rdv est uen résa ?
                If IfDate(rs.Fields("fin_reservation").Value).Length > 0 Then
                    ' confirmer la résa
                    szSQL = "UPDATE eleves_cpt SET fin_reservation=NULL, intitule=CONCAT('RESA ',getIntituleLigne(circuit,statut))" & _
                            " WHERE no_ligne=" & rs.Fields("no_ligne").Value
                    ExecQuery(ctDSN_AEM, szSQL)
                End If
            End If
            rs.MoveNext()
        Loop
        rs.Close()

        ' mémoriser la date de dernière validation
        szSQL = "CALL spUPD_LAST_VALIDATION(" & gUserAgence & ",'" & Format(TE_DATE.Value, "yyyy/MM/dd") & "')"
        ExecQuery(ctDSN_AEM, szSQL)
        Me.Cursor = Cursors.Default
        LoadPlanning()

    End Sub

    ''' <summary>
    ''' Checks whether the specified date is the second weekend day.
    ''' </summary>
    Private Function IsSecondWeekend(ByVal d As DateTime) As Boolean

        Return d.DayOfWeek = CType(CType(CAL_PLANNING.FirstWeekendDay + 1, Integer) Mod [Enum].GetValues(GetType(DayOfWeek)).Length, DayOfWeek)

    End Function

    Private Sub TE_DATE_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TE_DATE.LostFocus

        ' si affichage par Journée, traiter les changements de date
        If rb_JOURNEE.Checked Then
            ' dimanche ?
            If TE_DATE.Value.DayOfWeek = 0 Then
                TE_DATE.Value.AddDays(1)
            End If
            rb_JOURNEE_Click(sender, e)
        Else
            rb_SEMAINE_Click(sender, e)
        End If

    End Sub

    Private Sub CAL_PLANNING_DateClick(ByVal sender As Object, ByVal e As MindFusion.Scheduling.WinForms.ResourceDateEventArgs) Handles CAL_PLANNING.DateClick

        If rb_JOURNEE.Checked = True Then
            TE_CD_MON.Text = e.Resource.Id    ' Moniteur sélectionné
            TE_MONITEUR.Text = e.Resource.Name
        End If

        ' double-click ? 
        If e.Clicks = 2 And e.Button = System.Windows.Forms.MouseButtons.Left Then
            ' affichage journée, insérer nouveau rdv
            If IsUserAuthorised(2) = False Then
                Exit Sub
            End If
            If IsExported(TE_DATE.Value) = True Or IsValidated(TE_DATE.Value) = True Then
                MsgBox("Une journée postérieure est déjà validée ou exportée en compta.")
                Exit Sub
            End If
            ' afficher la ligne pour creation
            FrmPlanningBLigne.pNoLigne = 0
            FrmPlanningBLigne.pCD_MON = TE_CD_MON.Text
            FrmPlanningBLigne.pDateTime = e.Date
            FrmPlanningBLigne.ShowDialog()
            ' réaffiche la viewlist
            LoadPlanning()
        End If

    End Sub

    Private Sub CAL_PLANNING_Draw(ByVal sender As Object, ByVal e As MindFusion.Scheduling.WinForms.DrawEventArgs) Handles CAL_PLANNING.Draw

        Dim bounds As Rectangle = e.Bounds
        Dim g As MindFusion.Drawing.IGraphics = e.Graphics
        Dim r As Resource = e.Resource
        Dim Jour As Date = e.Date

        Select Case e.Element
            Case CustomDrawElements.ResourceViewRowHeader
                ' encadrer les nom des ressources
                g.FillRectangle(Brushes.White, e.Bounds)
                g.DrawString(r.Name, e.Style.HeaderFont, Brushes.Navy, _
                             New RectangleF(e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height), centered)
                g.DrawLine(Pens.Gray, e.Bounds.Left, e.Bounds.Bottom - 1, e.Bounds.Right - 1, e.Bounds.Bottom - 1)
                ' tracer une ligne sur bordure gauche
                g.DrawLine(Pens.Gray, e.Bounds.Right - 1, e.Bounds.Top, e.Bounds.Right - 1, e.Bounds.Bottom)

            Case CustomDrawElements.ResourceViewCell
                ' colorier la colonne
                Dim bcolor As Brush = Brushes.White
                If Jour.DayOfWeek = CAL_PLANNING.FirstWeekendDay Then
                    ' week-end
                    bcolor = Brushes.LightGray
                ElseIf IsHoliday(Jour) Then
                    ' jour férié 
                    bcolor = Brushes.LightSalmon
                End If
                If IsDayOff(r.Id, Jour) = True Then
                    ' jour de repos du moniteur ?
                    bcolor = Brushes.LightGray
                End If
                g.FillRectangle(bcolor, bounds)
                ' tracer une ligne sur bordure gauche
                g.DrawLine(Pens.Gray, e.Bounds.Right - 1, e.Bounds.Top, e.Bounds.Right - 1, e.Bounds.Bottom)

        End Select

        If CAL_PLANNING.CurrentView = CalendarView.Timetable Then
            bounds.Inflate(-1, -1)
            If IsDayOff(TE_CD_MON.Text, Jour.AddHours(e.StartTime.Hours)) = True Then
                ' jour de repos du moniteur ?
                e.Graphics.FillRectangle(Brushes.LightGray, bounds)
            Else
                e.Graphics.FillRectangle(Brushes.LightYellow, bounds)
            End If
            ' colorier les cellules selon les horaires : travail = jaune pale, non travail = fumée blanc
            If Jour = DateTime.Now.Date Then
                ' date du jour
                e.Graphics.FillRectangle(Brushes.Orange, bounds)
            ElseIf Jour.DayOfWeek = CAL_PLANNING.FirstWeekendDay Then
                ' week-end
                e.Graphics.FillRectangle(Brushes.LightGray, bounds)
            ElseIf IsHoliday(Jour) Then
                ' jour férié 
                e.Graphics.FillRectangle(Brushes.LightSalmon, bounds)
            End If
        End If

    End Sub

    Private Sub CAL_PLANNING_ItemClick(ByVal sender As Object, ByVal e As MindFusion.Scheduling.WinForms.ItemMouseEventArgs) Handles CAL_PLANNING.ItemClick

        If System.Windows.Forms.MouseButtons.Left Then
            ' Get the clicked event
            Dim app As Appointment = e.Item 'as Appointment
            If rb_JOURNEE.Checked = True Then
                TE_CD_MON.Text = app.Resources(0).Id   ' Moniteur sélectionné
                TE_MONITEUR.Text = app.Resources(0).Name
            End If
            ' double-click = Modifier
            If e.Clicks = 2 Then
                ' afficher les détails de la ligne NoLigne
                FrmPlanningBLigne.pNoLigne = app.Id
                FrmPlanningBLigne.pCD_MON = TE_CD_MON.Text
                FrmPlanningBLigne.pDateTime = app.StartTime.Date
                FrmPlanningBLigne.ShowDialog()
                ' réaffiche la viewlist
                LoadPlanning()
            End If
        End If

    End Sub

    Private Sub CAL_PLANNING_ItemDeleting(ByVal sender As Object, ByVal e As MindFusion.Scheduling.WinForms.ItemConfirmEventArgs) Handles CAL_PLANNING.ItemDeleting

        e.Confirm = False

        If gUserAcces < 4 Then
            Exit Sub
        End If

        ' Lire le rendez-vous sélectionné
        szSQL = "CALL spGet_ELEVES_CPT_byNO_LIGNE(" & e.Item.Id & ")"
        GetRecordset(ctDSN_AEM, szSQL, rs)
        If rs.RecordCount <= 0 Then
            rs.Close()
            Exit Sub
        End If

        ' journée déjà comptabilisée ?
        If IsDate(rs.Fields("date_valeur").Value) Then
            MsgBox("Journée déjà validée", MsgBoxStyle.Critical)
            Exit Sub
        End If
        ' utilistaeur non manager ?
        If gUserAcces < 9 And IsEleve(CInt(e.Item.Tag)) Then
            ' controler le délai annulation ?
            If IsDelaiOK(e.Item.StartTime.Date, setModifiedBy(rs.Fields("cree_le").Value, rs.Fields("modif_le").Value, rs.Fields("cd_uti").Value), _
                         rs.Fields("statut").Value) = False Then
                Exit Sub
            End If
        End If
        If MessageBox.Show("Etes-vous sûr de vouloir supprimer le rdv de " & rs.Fields("nom").Value & " ?", "Confirmation de la suppression", _
                             MessageBoxButtons.OKCancel, MessageBoxIcon.Question) = Windows.Forms.DialogResult.OK Then
            ' delettrer la ligne de compte
            szSQL = "CALL spUPD_ELEVES_DELETTRER(" & rs.Fields("no_ligne").Value & ")"
            ExecQuery(ctDSN_AEM, szSQL)

            ' mise à jour de la ligne comme annulée
            szSQL = "UPDATE eleves_cpt SET ref='',debit=0,mtval=0,qte=0,noplan=0,fin_reservation=NULL,intitule='RDV de " & _
                     rs.Fields("noplan").Value & " h annulé (" & rs.Fields("statut").Value & ")', cd_uti='" & gUserCode & _
                    "' WHERE no_ligne=" & rs.Fields("no_ligne").Value
            If ExecQuery(ctDSN_AEM, szSQL) Then
                ' suppression confirmée
                e.Confirm = True
            End If
        End If
        rs.Close()
        rs = Nothing

    End Sub

    Private Sub CAL_PLANNING_ItemModifying(ByVal sender As Object, ByVal e As MindFusion.Scheduling.WinForms.ItemModifyConfirmEventArgs) Handles CAL_PLANNING.ItemModifying

        ' si heure d'un élève ou élève provisoire, interdire modif
        If IsEleve(CInt(e.Item.Tag)) Or CInt(e.Item.Tag) = 8 Then
            e.Confirm = False
        End If
        '' si affichage par semaine, interdire modif
        'If rb_SEMAINE.Checked Then
        '    e.Confirm = False
        'End If
        If IsExported(TE_DATE.Value) Or IsValidated(TE_DATE.Value) Then
            e.Confirm = False
        End If

    End Sub

    Private Sub CAL_PLANNING_ItemModified(ByVal sender As Object, ByVal e As MindFusion.Scheduling.WinForms.ItemModifiedEventArgs) Handles CAL_PLANNING.ItemModified

        Dim app As Appointment = e.Item 'as Appointment

        ' mettre à jpur le rendez-vous suite à un move ou resize 
        If rb_JOURNEE.Checked Then
            szSQL = "UPDATE eleves_cpt SET qte=" & app.EndTime.Hour - app.StartTime.Hour & _
                    ", noplan=" & app.StartTime.Hour & ", cd_mon='" & app.Resources(0).Id & _
                    "', cd_uti='" & gUserCode & "' WHERE no_ligne=" & app.Id
            ExecQuery(ctDSN_AEM, szSQL)
        Else
            szSQL = "UPDATE eleves_cpt SET qte=" & app.EndTime.Hour - app.StartTime.Hour & _
                    ", noplan=" & app.StartTime.Hour & ", cd_mon='" & TE_CD_MON.Text & _
                    "', cd_uti='" & gUserCode & "' WHERE no_ligne=" & app.Id
            ExecQuery(ctDSN_AEM, szSQL)
        End If

    End Sub

    Private Sub BO_PREC_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BO_PREC.Click
        If rb_JOURNEE.Checked Then
            '' c'est un lundi ? 
            'If CAL_PLANNING.Date.DayOfWeek = 1 Then
            '    ' recule le planning de 2 jours
            '    TE_DATE.Value = CAL_PLANNING.Date.AddDays(-2)
            'Else
            ' recule le planning d'un jour
            TE_DATE.Value = CAL_PLANNING.Date.AddDays(-1)
            'End If
            rb_JOURNEE_Click(sender, e)
        Else
            ' recule le planning de 7 jours
            TE_DATE.Value = CAL_PLANNING.Date.AddDays(-7)
            rb_SEMAINE_Click(sender, e)
        End If

    End Sub

    Private Sub BO_SUIVANT_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BO_SUIVANT.Click
        If rb_JOURNEE.Checked Then
            '' c'est un samedi ? 
            'If CAL_PLANNING.Date.DayOfWeek = 6 Then
            '    ' avance le planning de 2 jours
            '    TE_DATE.Value = CAL_PLANNING.Date.AddDays(2)
            'Else
            ' avance le planning d'un jour
            TE_DATE.Value = CAL_PLANNING.Date.AddDays(1)
            'End If
            rb_JOURNEE_Click(sender, e)
        Else
            ' avance le planning de 7 jours
            TE_DATE.Value = CAL_PLANNING.Date.AddDays(7)
            rb_SEMAINE_Click(sender, e)
        End If

    End Sub

    Private Function getFirstLine(ByVal szText As String) As String
        ' retourne le texte précédent le caractère vbNewLine
        getFirstLine = Mid(szText, 1, InStr(szText, vbNewLine))
    End Function

    Private Sub rb_JOURNEE_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles rb_JOURNEE.Click
        ' affichage par Journée
        CAL_PLANNING.CurrentView = CalendarView.ResourceView
        CAL_PLANNING.GroupType = GroupType.GroupByResources
        CAL_PLANNING.ResourceViewSettings.TimelineScale = 190
        CAL_PLANNING.ResourceViewSettings.BottomTimelineSettings.Format = "H:mm"
        CAL_PLANNING.Date = Format(TE_DATE.Value, "yyyy/MM/dd")
        CAL_PLANNING.EndDate = CAL_PLANNING.Date.AddHours(23)
        CAL_PLANNING.CurrentTime = TE_DATE.Value
        BO_VALIDER.Visible = True
        BO_SEMAINE_TYPE.Visible = False
        LoadPlanning()
    End Sub

    Private Sub rb_SEMAINE_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles rb_SEMAINE.Click
        Dim i As Integer

        If TE_CD_MON.Text.Length = 0 Then
            MsgBox("Sélectionner d'abord un des moniteurs en cliquant sur son nom.")
            Exit Sub
        End If

        ' affichage sur 6 jours
        CAL_PLANNING.CurrentView = CalendarView.Timetable
        CAL_PLANNING.GroupType = GroupType.None
        CAL_PLANNING.TimetableSettings.Dates.Clear()
        CAL_PLANNING.Date = getLundiPrecedent(TE_DATE.Value)
        For i = 0 To 5
            CAL_PLANNING.TimetableSettings.Dates.Add(CAL_PLANNING.Date.AddDays(i))
        Next i
        CAL_PLANNING.EndDate = CAL_PLANNING.Date.AddDays(5)

        CAL_PLANNING.CurrentTime = TE_DATE.Value
        BO_VALIDER.Visible = False
        'BO_SEMAINE_TYPE.Visible = True
        LoadPlanning()
    End Sub

    Private Sub LoadRendezVous(ByVal debut As Date, ByVal fin As Date, ByVal moniteur As String, ByVal noResource As Integer)
        Dim rsRDV As ADODB.Recordset = Nothing
        Dim app As Appointment

        ' Lire la journée du planning
        szSQL = "CALL spGet_ELEVES_CPT_byPLANNING(" & gUserAgence & ",'" & _
                 Format(debut, "yyyy/MM/dd") & "','" & Format(fin, "yyyy/MM/dd") & "','" & moniteur & "')"
        GetRecordset(ctDSN_AEM, szSQL, rsRDV)

        Do While Not rsRDV.EOF
            app = New Appointment()
            Dim jour As Date = rsRDV.Fields("date").Value
            app.StartTime = New Date(jour.Year, jour.Month, jour.Day, rsRDV.Fields("noplan").Value, 0, 0)
            app.EndTime = app.StartTime.AddHours(rsRDV.Fields("qte").Value)
            app.HeaderText = Mid(rsRDV.Fields("nom").Value, 1, 15)
            If rb_JOURNEE.Checked = True Then
                app.Resources.Add(CAL_PLANNING.Resources(noResource))
            End If
            app.Tag = rsRDV.Fields("cd_cli").Value
            app.Id = rsRDV.Fields("no_ligne").Value

            ' colorier la cellule selon le statut du RDV
            Dim bcolor As MindFusion.Drawing.SolidBrush

            If IsDate(rsRDV.Fields("date_valeur").Value) Then
                ' rdv validé = vert pale
                bcolor = New MindFusion.Drawing.SolidBrush(Color.LightGreen)
            Else
                If Val(rsRDV.Fields("ref").Value) <> rsRDV.Fields("cd_cli").Value Then
                    If rsRDV.Fields("statut").Value > 1 Or IfDate(rsRDV.Fields("fin_reservation").Value).Length > 0 Then
                        ' rdv élève décommandé ou résa = rose pale
                        bcolor = New MindFusion.Drawing.SolidBrush(Color.LightPink)
                    Else
                        ' rdv élève = jaune pale
                        bcolor = New MindFusion.Drawing.SolidBrush(Color.LightYellow)
                        Select Case rsRDV.Fields("circuit").Value
                            Case 1
                                bcolor = New MindFusion.Drawing.SolidBrush(Color.Gold)
                            Case 2
                                bcolor = New MindFusion.Drawing.SolidBrush(Color.Plum)
                            Case 3
                                bcolor = New MindFusion.Drawing.SolidBrush(Color.YellowGreen)
                            Case 4
                                bcolor = New MindFusion.Drawing.SolidBrush(Color.DeepSkyBlue)
                            Case 5
                                bcolor = New MindFusion.Drawing.SolidBrush(Color.LimeGreen)
                        End Select
                    End If
                Else
                    ' activité = couleur bleu ciel
                    bcolor = New MindFusion.Drawing.SolidBrush(Color.LightBlue)
                End If
            End If
            If rb_JOURNEE.Checked = True Then
                app.Style.HeaderBrush = bcolor
            Else
                app.Style.Brush = bcolor
            End If
            app.AllowChangeEnd = True
            app.AllowChangeStart = True
            app.AllowMove = True
            app.AllDayEvent = False
            CAL_PLANNING.Schedule.Items.Add(app)
            rsRDV.MoveNext()
        Loop
        ' Close the recordset AND connection.
        rsRDV.Close()


    End Sub

    Private Sub CAL_PLANNING_ResourceViewRowHeaderClick(ByVal sender As Object, ByVal e As MindFusion.Scheduling.WinForms.ResourceDateEventArgs) Handles CAL_PLANNING.ResourceViewRowHeaderClick
        TE_CD_MON.Text = e.Resource.Id    ' Moniteur sélectionné
        TE_MONITEUR.Text = e.Resource.Name
    End Sub

    Private Sub BO_ABSENCES_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BO_IMPRIMER.Click
        ' Editions des états de la rubrique
        gDate_debut = TE_DATE.Value
        gMoniteur1 = TE_CD_MON.Text
        FrmEditions.pRubrique = "PLAN_B"
        FrmEditions.pParametres = ""
        FrmEditions.ShowDialog()
    End Sub

    Private Sub BO_DEVALIDER_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BO_DEVALIDER.Click

        ' Dévalider une journée B
        If IsUserAuthorised(9) = False Then
            Exit Sub
        End If

        If IsExported(TE_DATE.Value) Then
            Exit Sub
        End If

        If MsgBox("Cette action va annuler la validation de la journée du " & Format(TE_DATE.Value, "dd/MM/yyyy") & "." & vbCrLf & _
                  "Etes-vous sûr de vouloir dé-valider cette journée ?", _
                  MsgBoxStyle.YesNo, "Confirmation de la dé-validation") = MsgBoxResult.No Then
            Exit Sub
        End If

        Me.Cursor = Cursors.WaitCursor
        ' marquer la ligne plannig comme dévalidée
        szSQL = "UPDATE eleves_cpt SET date_valeur = NULL, statut = 0 WHERE agence = " & gUserAgence & " AND date = '" & Format(TE_DATE.Value, "yyyy/MM/dd") & _
                "' AND statut=1 AND noplan AND qte"
        ExecQuery(ctDSN_AEM, szSQL)
        Me.Cursor = Cursors.Default
        ' réaffiche le planning
        LoadPlanning()

    End Sub

    Function IsDayOff(ByVal code As String, ByVal Jour As Date) As Boolean
        Dim rsAff As ADODB.Recordset = Nothing

        IsDayOff = True

        ' Lire l'affectation du moniteur à ce jour
        szSQL = "SELECT * FROM MONITEURS_AFF WHERE cd_mon='" & code & "' AND agence = " & gUserAgence & " AND dated <= '" & _
                Format(Jour, "yyyy/MM/dd") & "' AND datef >= '" & Format(Jour, "yyyy/MM/dd") & "'"
        GetRecordset(ctDSN_AEM, szSQL, rsAff)
        If rsAff.RecordCount < 1 Then
            ' affectation non trouvée, sortir dayoff
            Exit Function
        Else
            ' Ce jour est-il un jour de repos du moniteur ?
            Select Case Jour.DayOfWeek
                Case 1
                    If rsAff.Fields("repos1").Value <> False Then
                        ' oui, sortir dayoff
                        Exit Function
                    End If
                Case 2
                    If rsAff.Fields("repos2").Value <> False Then
                        Exit Function
                    End If
                Case 3
                    If rsAff.Fields("repos3").Value <> False Then
                        Exit Function
                    End If
                Case 4
                    If rsAff.Fields("repos4").Value <> False Then
                        Exit Function
                    End If
                Case 5
                    If rsAff.Fields("repos5").Value <> False Then
                        Exit Function
                    End If
                Case 6
                    If rsAff.Fields("repos6").Value <> False Then
                        Exit Function
                    End If
            End Select
            ' cette heure est-elle horsAff de ses horaires de travail ?
            If Jour.Hour < rsAff.Fields("dmatin").Value Or (Jour.Hour >= rsAff.Fields("fmatin").Value And Jour.Hour < rsAff.Fields("dsoir").Value) Or Jour.Hour >= rsAff.Fields("fsoir").Value Then
                Exit Function
            End If
        End If
        rsAff.Close()
        rsAff = Nothing

        IsDayOff = False

    End Function

    Private Sub BO_SEMAINE_TYPE_Click(sender As System.Object, e As System.EventArgs) Handles BO_SEMAINE_TYPE.Click

        Me.Cursor = Cursors.WaitCursor
        szSQL = "CALL spINS_PLANNING_B_TYPE(" & gUserAgence & ",'" & TE_CD_MON.Text & "','" & _
                Format(CAL_PLANNING.TimetableSettings.Dates(0), "yyyy/MM/dd") & "','" & gUserCode & "')"
        ExecQuery(ctDSN_AEM, szSQL)
        Me.Cursor = Cursors.Default
        ' réaffiche le planning
        LoadPlanning()

    End Sub
End Class